<?php
/**
 * 竞品规格控制器
 */

namespace app\admin\controller;

use app\common\model\Spec;
use app\common\validate\SpecValidate;
use Exception;
use think\db\Query;
use think\Request;
use think\response\Json;

class SpecController extends AdminBaseController {

	/**
	 * 列表
	 * @param Request $request
	 * @param Spec $model
	 * @return string
	 * @throws Exception
	 */
	public function index(Request $request, Spec $model): string {
		$param = $request->param();
		$data = $model->scope('where', $param)
			->paginate([
				'list_rows' => $this->admin['admin_list_rows'],
				'var_page' => 'page',
				'query' => $request->get(),
			]);
		// 关键词，排序等赋值
		$this->assign($request->get());

		$this->assign([
			'data' => $data,
			'page' => $data->render(),
			'total' => $data->total(),

		]);
		return $this->fetch();
	}

	/**
	 * 添加
	 * @param Request $request
	 * @param Spec $model
	 * @param SpecValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function add(Request $request, Spec $model, SpecValidate $validate) {
		if ($request->isPost()) {
			$param = $request->param();
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}

			$result = $model::create($param);

			$url = URL_BACK;
			if (isset($param['_create']) && (int) $param['_create'] === 1) {
				$url = URL_RELOAD;
			}
			return $result ? admin_success('添加成功', [], $url) : admin_error();
		}

		return $this->fetch();
	}

	/**
	 * 修改
	 * @param $id
	 * @param Request $request
	 * @param Spec $model
	 * @param SpecValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function edit($id, Request $request, Spec $model, SpecValidate $validate) {
		$data = $model->findOrEmpty($id);
		if ($request->isPost()) {
			$param = $request->param();
			$check = $validate->scene('admin_edit')->check($param);
			if (!$check) {
				return admin_error($validate->getError());
			}

			$result = $data->save($param);

			return $result ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');
		}

		$this->assign([
			'data' => $data,

		]);

		return $this->fetch('add');
	}

	/**
	 * 删除
	 * @param mixed $id
	 * @param Spec $model
	 * @return Json
	 */
	public function del($id, Spec $model): Json {
	    return admin_error('存在关联数据,请删除关联数据再删除');
		$check = $model->inNoDeletionIds($id);
		if (false !== $check) {
			return admin_error('ID为' . $check . '的数据不能被删除');
		}

		$result = $model::destroy(static function ($query) use ($id) {
			/** @var Query $query */
			$query->whereIn('id', $id);
		});

		return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
	}

	public function import(Request $request): Json {

		$param = $request->param();

		$field_list = ['name'];
		$result = $this->importData('file', 'spec', $field_list);

		return true === $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error($result);
	}
}
